package com.lllmark.lllmarkDemo.rest;

import com.lllmark.lllmarkDemo.component.RedisComponent;
import com.lllmark.lllmarkDemo.config.AppConfig;
import com.lllmark.lllmarkDemo.constans.Constans;
import com.lllmark.lllmarkDemo.entity.dto.UserDTO;
import com.lllmark.lllmarkDemo.entity.po.User;
import com.lllmark.lllmarkDemo.entity.vo.UserVO;
import com.lllmark.lllmarkDemo.service.serviceImpl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作接口
 *
 * Author: Hanqingsong
 * Date: 13:55 2024/4/8
 */
@Api(tags = "用户curd接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class DBController extends BaseController {

    @Autowired
    private UserServiceImpl userService;

    // 项目基本配置
    @Autowired
    private AppConfig appConfig;

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 分页查询
     * @return
     */
    @PostMapping("/selectAll")
    @ApiOperation("分页查询")
    public Map<String, Object> selectAll(@RequestBody UserDTO userDTO){
        System.out.println(userDTO);
        List<UserVO> users = userService.slectAll(userDTO);
        if (!users.isEmpty()){
            return success(users);
        }
        return failed(Constans.FAILED_CODE, Constans.FAILED_MESSAGE);
    }

    /**
     * 返回用户数量
     * @return
     */
    @GetMapping("/getUserCounts")
    public Map<String, Object> getUserCounts(){
        Integer counts = userService.getUserCounts();
        if (counts != null){
            return success(counts);
        }
        return failed(Constans.FAILED_CODE, Constans.FAILED_MESSAGE);
    }

    /**
     * 按id查询, 首先查询redis中有无当前用户的信息,
     * 如果不存在, 那么从数据库中查出该用户的信息,然后再塞到redis中
     * 如果存在, 那么直接从redis中取出改用户信息
     * @param id
     * @return
     */
    @GetMapping("/selectById/{id}")
    @ApiOperation("按id查询")
    public Map<String, Object> selectById(@PathVariable Integer id){
        UserVO user = redisComponent.getUserById(String.valueOf(id));
//        UserVO user = userService.selectById(id);
        if (user != null){
            return success(user);
        }
        return failed(Constans.FAILED_CODE, Constans.FAILED_MESSAGE);
    }

    /**
     * 获取用户头像
     * @param response
     * @param id
     */
    @ApiOperation("获取用户头像")
    @GetMapping("/getUserAvatar/{id}")
    public void getAvatar(HttpServletResponse response, @PathVariable String id) {
        String avatarFolderName = Constans.FILE_FOLDER_FILE + Constans.FILE_FOLDER_AVATAR_NAME;
        File folder = new File(appConfig.getProjectFolder() + avatarFolderName);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String avatarPath = appConfig.getProjectFolder() + avatarFolderName + id + Constans.AVATAR_SUFFIX;
        File file = new File(avatarPath);
        if (!file.exists()) {
            String default_avatar_path = appConfig.getProjectFolder() + avatarFolderName + Constans.AVATAR_DEFUALT;
            if (!new File(default_avatar_path).exists()) {
                response.setHeader(Constans.CONTENT_TYPE, Constans.CONTENT_TYPE_VALUE);
                response.setStatus(HttpStatus.OK.value());
                PrintWriter writer = null;
                try {
                    writer = response.getWriter();
                    writer.print("请在头像目录下放置默认头像default_avatar.jpg");
                    writer.close();
                } catch (Exception e) {
                    log.error("输出默认图失败");
                    e.printStackTrace();
                } finally {
                    writer.close();
                }
                return;
            }
            avatarPath = appConfig.getProjectFolder() + avatarFolderName + Constans.AVATAR_DEFUALT;
        }
        response.setContentType("image/jpg");
        readFile(response, avatarPath);
    }

    /**
     * 单个用户修改
     * @param userDTO
     * @return
     */
    @ApiOperation("修改用户信息")
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody UserDTO userDTO){
        Integer flag = userService.update(userDTO);
        if (flag == 1){
            return success(flag);
        }
        return failed(Constans.FAILED_CODE, Constans.FAILED_MESSAGE);
    }

    /**
     * 删除单个用户
     * @param id
     * @return
     */
    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteById(@PathVariable Integer id){
        Integer flag = userService.deleteById(id);
        if (flag == 1){
            return success(flag);
        }
        return failed(Constans.FAILED_CODE, Constans.FAILED_MESSAGE);
    }



    /**
     * 新增用户
     * @param user
     * @return
     */
    @ApiOperation("新增用户")
    @PutMapping("/insert")
    public Map<String, Object> insert(@RequestBody User user){
        Integer flag = userService.insert(user);
        if (flag == 1){
            return success(flag);
        }
        return failed(Constans.FAILED_CODE, Constans.FAILED_MESSAGE);
    }

}
